package crm8000.services

import org.springframework.web.context.request.RequestContextHolder;

import crm8000.Models.Org;
import crm8000.Models.User;
import crm8000.helper.Result
import grails.transaction.Transactional

@Transactional
class UserService {

    def doLogin(String loginName, String password) {
		def user = User.findByLoginNameAndPassword(loginName, password.encodeAsMD5())
		
		if (user) {
			this.session.loginUserId = user.id
			this.session.loginUserName = user.name
			return new Result(success: true)
		} else {
			return new Result(success: false, msg: "用户名或者密码错误")
		}
    }
	
	def getSession(){
		RequestContextHolder.currentRequestAttributes().getSession()
	}
	
	def getLoginUserName() {
		return this.session.loginUserName
	}
	
	def getLoginUserId() {
		return this.session.loginUserId
	}
	
	def clearLoginUserInSession() {
		this.session.loginUserId = null
		this.session.loginUserName = null
	}
	
	def changeMyPassword(String userId, String oldPassword, String newPassword) {
		if (this.loginUserId != userId) {
			return new Result(success: false, msg: "当前用户Session失效，请重新登录系统")	
		}
		
		def user = User.findByUserIdAndPassword(userId, oldPassword.encodeAsMD5())
		
		if (!user) {
			return new Result(success: false, msg: "旧密码错误")
		}
		
		user.password = newPassword.encodeAsMD5()
		user.save()
		
		return new Result(success: true)
	}
	
	def allOrgs() {
		def result = []

		// 目前组织结构最大只能为3级		
		def orgList1 = Org.findAllByParentId(null, [sort: 'orgCode'])
		
		for (org1 in orgList1) {
			result.add(org1)
			def orgList2 = Org.findAllByParentId(org1.id, [sort: 'orgCode'])
			org1.leaf = orgList2.size() == 0
			for (org2 in orgList2) {
				org1.children.add(org2)
				def orgList3 = Org.findAllByParentId(org2.id, [sort: 'orgCode'])
				org2.leaf = orgList3.size() == 0
				
				for (org3 in orgList3) {
					org2.children.add(org3)
				}
			}
		}
		
		return result
	}
	
	def allUsers(orgId) {
		return User.findAllByOrg(Org.get(orgId), [sort: 'orgCode'])
	}
}
